<template>
  <div class="warehousearea">
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.shifttasksettings_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <!-- 姓名自定义-->
      <template slot="xmForm" slot-scope="scope">
        <el-select
          placeholder="请输入姓名（组长）"
          v-model="scope.row['xm']"
          filterable
          clearable
          size="small">
          <el-option
            v-for="(item, index) in getXm"
            :key="index"
            :value="item.realName"
          >
          </el-option>
        </el-select>
      </template>
      <!-- 任务时间设置 -->
      <template slot="dwryxxForm">
        <div>
          <el-button
            type="primary"
            size="small"
            :disabled="dialogType === viewLabel"
            @click="addControlPerson()">
            添 加
          </el-button>
        </div>
      </template>
      <!-- 队伍人员内容表单自定义 -->
      <template slot="dwryxxContentForm">
        <div class="dwryxxContent_div">
          <avue-crud
            :option="personOption"
            :data="personData"
            ref="personCrud"
          >
            <!-- 自定义操作列：删除按钮 -->
            <template slot="menu" slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                :disabled="dialogType === viewLabel"
                @click="handleDeletePerson(scope.row, scope.index)">
                删 除
              </el-button>
            </template>

            <!-- 任务开始时间 -->
            <template slot="qssj" slot-scope="scope">
              <el-select
                v-if="!obj.value"
                placeholder="请输入开始时间"
                v-model="scope.row['qssj']"
                clearable
                size="small">
                <el-option
                  v-for="(item, index) in getRenwuTime"
                  :key="index"
                  :label="item.dictValue"
                  :value="item.dictKey"
                >
                </el-option>
              </el-select>
              <el-time-picker
                v-if="obj.value"
                placeholder="请输入开始时间"
                v-model="scope.row['qssj']"
                clearable
                size="small">
              </el-time-picker>
            </template>
            <!-- 任务结束时间 -->
            <template slot="jssj" slot-scope="scope">
              <el-select
                v-if="!obj.value"
                placeholder="请输入结束时间"
                v-model="scope.row['jssj']"
                clearable
                size="small">
                <el-option
                  v-for="(item, index) in getRenwuTime"
                  :key="index"
                  :label="item.dictValue"
                  :value="item.dictKey"
                >
                </el-option>
              </el-select>
              <el-time-picker
                v-if="obj.value"
                placeholder="请输入结束时间"
                v-model="scope.row['jssj']"
                clearable
                size="small">
              </el-time-picker>
            </template>


          </avue-crud>
        </div>
      </template>

      <template slot="idsLabel">
        <span style="color:#F56C6C">*</span><span>巡检点:</span>
      </template>
      <template slot="idsForm">
        <div v-if="dialogType !== 'view'">
          <el-form label-width="0px">
            <el-button
              type="success"
              size="small"
              @click="handlePointcustom">
              选择巡检点
            </el-button>
            <span v-if="pointcustomTagsErr" class="dsc_error">请选择巡检点</span>
            <div class="dcs_point_list">
              <el-tag
                :key="index"
                v-for="(tag, index) in pointcustomTags"
                closable
                :disable-transitions="false"
                @close="closePointcustomTag(index)">
                {{tag.dwmc}}
              </el-tag>
            </div>
          </el-form>
        </div>
      </template>
    </avue-crud>

    <!-- 选择巡检点弹窗 -->
    <el-dialog
      title="选择巡检点"
      :visible.sync="dialogPointcustom"
      append-to-body
      @close='closeDialog'
      width="1200px"
    >
      <avue-crud
        :option="pointcustomOption"
        :table-loading="pointcustomLoading"
        :data="pointcustomData"
        :page.sync="pointcustomPage"
        ref="pointcustomCrud"
        @search-change="pointcustomSearchChange"
        @search-reset="pointcustomSearchReset"
        @selection-change="pointcustomSelectionChange"
        @current-change="pointcustomCurrentChange"
        @size-change="pointcustomSizeChange"
      >
      </avue-crud>

      <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="choosePointcustom()">确 定</el-button>
        </span>
    </el-dialog>
  </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove, getFzrLinkInfo, getName} from "@/api/xjgl/shifttasksettings";
  import {mapGetters} from "vuex";
  import {getTimeMonth, getTimeWeek, getTimeYear, getXjdList} from "../../api/xjgl/shifttasksettings";
  import {validateIsInteger} from "../../api/mmhi/validate";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "姓名（组长）",
              prop: "xm",
              filterable:true,
              search: true,
              // formslot: true,
              align:"center",
              maxlength:50,
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入姓名（组长）",
                trigger: "blur"
              }]
            },
            {
              label: "所在部门",
              prop: "szbm",
              align: "center",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入所在部门",
                trigger: "blur"
              }]
            },
            {
              label: "岗位名称",
              prop: "gwmc",
              disabled: true,
              hide: true,
              align: "center",
              rules: [{
                required: true,
                message: "请输入岗位名称",
                trigger: "blur"
              }]
            },
            {
              label: "工号",
              prop: "gh",
              align: "center",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入工号",
                trigger: "blur"
              }]
            },
            {
              label: "联系电话",
              prop: "lxdh",
              align: "center",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入联系电话",
                trigger: "blur"
              }]
            },
            {
              label: "班组其他成员",
              prop: "bzqtcy",
              hide: true,
              align:"center",
              maxlength:50,
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入班组其他成员",
                trigger: "blur"
              }]
            },
            {
              label: "检查频次",
              prop: "jcpc",
              align: "center",
              search: true,
              type:"select",
              dataType: "number",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=jcpc",
              change:({value}) => {
                  if(value == 1){
                    this.obj.value = true;
                  }
                  else{
                    this.obj.value = false;
                  }
              },
              //   function(e){
              //   if(e.value == 1){
              //     //this.IsDateCheck = true;
              //     this.$set(this.obj, "value",true);
              //     console.log('true');
              //   }
              //   else{
              //     //this.IsDateCheck = false;
              //     this.$set(this.obj, "value",false);
              //     console.log('false');
              //   }
              //   console.log(this.IsDateCheck);
              // },
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入检查频次",
                trigger: "blur"
              }]
            },
            {
              label: "检查次数",
              prop: "jccs",
              align: "center",
              rules: [{
                required: true,
                validator:validateIsInteger,
                trigger: "blur"
              }]
            },
            {
              label: "任务设置",
              prop: "dwryxx",
              align: "center",
              labelWidth:120,
              span: 24,
              hide: true,
              formslot: true
            },
            {
              label: "",
              prop: "dwryxxContent",
              align: "center",
              span: 24,
              hide: true,
              formslot: true
            },
            {
              label: "巡检点",
              prop: "dwbh",
              hide: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false
            },
            {
              label: "选择巡检点",
              prop: "ids",
              align: "center",
              hide: true,
              viewDisplay: false,
              formslot:true,
              labelslot:true,
            },
          ]
        },
        data: [],
        getXm:[],
        getRenwuTime:[],
        IsDateCheck : false,
        obj:{
          value:true
        },

        dialogPointcustom: false,
        pointcustomQuery: {},
        pointcustomLoading: true,
        pointcustomPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        pointcustomSelectionList: [],
        pointcustomOption: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          addBtn:false,
          menu: false,
          viewBtn: false,
          editBtn:false,
          delBtn:false,
          selection: true,
          columnBtn: false,
          dialogClickModal: false,
          column: [
            {
              label: "点位类型",
              prop: "dwlx",
              type: "select",
              formslot: true,
              search: true,
              align: "center",
              dataType:"number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pointCustomSettings_dwlx",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请选择点位类型",
                trigger: "blur"
              }]
            },
            {
              label: "点位名称",
              prop: "dwmc",
              search: true,
              align: "center",
              rules: [{
                required: true,
                message: "请输入点位名称",
                trigger: "blur"
              }]
            },
            {
              label: "点位编号",
              prop: "dwbh",
              align: "center",
              rules: [{
                required: true,
                message: "请输入点位编号",
                trigger: "blur"
              }]
            }
          ]
        },
        pointcustomData: [],
        pointcustomTags: [],
        pointcustomTagsErr: false,
        selectPointcustom: {},


        // 任务设置
        personData: [],
        personOption: {
          calcHeight: 30,
          tip: false,
          index: true,
          selection: false,
          addBtn: false,
          refreshBtn: false,
          columnBtn: false,
          indexWidth: 30,
          editBtn: false,
          delBtn: false,
          menuWidth: 100,
          column: [
            {
              label: "开始时间",
              prop: "qssj",
              align:"center",
              slot:true,
              maxlength:50,
            },
            {
              label: "结束时间",
              prop: "jssj",
              align:"center",
              slot:true,
              maxlength:25,
            },
          ]
        },
        dialogType: "",
        viewLabel: "view",
      };
    },
    watch: {
      'form.xm':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{
              this.form.szbm = res.data.data[0].deptName;
              this.form.gwmc = res.data.data[0].postName;
              this.form.gh = res.data.data[0].code;
              this.form.lxdh = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      },
      'form.jcpc':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            if(val==2){
              getTimeWeek()
                .then(res => {
                  this.getRenwuTime = res.data.data;
                })
                .then(() => {
                  this.onLoad(this.page);
                });
            }
            if(val==3){
              getTimeMonth()
                .then(res => {
                  this.getRenwuTime = res.data.data;
                })
                .then(() => {
                  this.onLoad(this.page);
                });
            }
            if(val==4){
              getTimeYear()
                .then(res => {
                  this.getRenwuTime = res.data.data;
                })
                .then(() => {
                  this.onLoad(this.page);
                });
            }
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.shifttasksettings_add, false),
          viewBtn: this.vaildData(this.permission.shifttasksettings_view, false),
          delBtn: this.vaildData(this.permission.shifttasksettings_delete, false),
          editBtn: this.vaildData(this.permission.shifttasksettings_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      // this.getTimes();
      // this.getTimesM();
      // this.getTimesY()
      this.getNames();
    },
    methods: {

      // 删除巡检任务时间
      handleDeletePerson(row, index) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.personData.splice(index, 1);
        });
      },
      // 添加巡检任务时间
      addControlPerson() {
        this.personData.push({
          qssj: "",
          jssj: "",
        });
      },
     //获取姓名
      getNames() {
        getName()
          .then(res => {
            this.getXm = res.data.data;
          })
          .then(() => {
            this.onLoad(this.page);
          });
      },
      // getTimesM() {
      //   getTimeMonth()
      //     .then(res => {
      //       this.getRenwuTime = res.data.data;
      //     })
      //     .then(() => {
      //       this.onLoad(this.page);
      //     });
      // },
      // getTimesY() {
      //   getTimeYear()
      //     .then(res => {
      //       this.getRenwuTime = res.data.data;
      //     })
      //     .then(() => {
      //       this.onLoad(this.page);
      //     });
      // },

      // 打开选择巡检点弹窗
      handlePointcustom() {
        this.dialogPointcustom = true;
        this.pointcustomOnLoad(this.pointcustomPage);
      },
      // 关闭选择巡检点弹窗
      closeDialog() {
        this.pointcustomPage.currentPage = 1;
        this.dialogPointcustom = false;
        this.pointcustomSelectionClear();
      },
      // 巡检点获取表格数据
      pointcustomOnLoad(page, params = {}) {
        this.pointcustomLoading = true;
        getXjdList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.pointcustomPage.total = data.total;
          this.pointcustomData = data.records;
          this.pointcustomLoading = false;
          if(this.selectPointcustom !== undefined && JSON.stringify(this.selectPointcustom) !== "{}"  &&  this.pointcustomTags.length !== 0) {
            this.$nextTick(() => {
              this.pointcustomData.forEach(row => {
                if(this.selectPointcustom[row.id] !== undefined) {
                  this.$refs.pointcustomCrud.toggleRowSelection(row, true);
                }
              })
            })
          }
        });
      },

      // 巡检点清空勾选
      pointcustomSelectionClear() {
        this.pointcustomSelectionList = [];
        this.$refs.pointcustomCrud.toggleSelection();
      },

      // 巡检点搜索条件改变事件
      pointcustomSearchChange(params, done) {
        this.pointcustomQuery = params;
        this.pointcustomPage.currentPage = 1;
        this.pointcustomOnLoad(this.pointcustomPage, params);
        done();
      },

      // 巡检点清空搜索条件
      pointcustomSearchReset() {
        this.pointcustomQuery = {};
        this.pointcustomOnLoad(this.pointcustomPage);
      },

      // 巡检点勾选
      pointcustomSelectionChange(list) {
        this.pointcustomSelectionList = list;
      },

      // 巡检点换页数
      pointcustomCurrentChange(currentPage){
        var pageSelectIds = [];
        var pageAllIds = [];
        this.pointcustomSelectionList.forEach(item => {
          this.selectPointcustom[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.pointcustomData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(var id in this.selectPointcustom) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectPointcustom[id];
          }
        }
        this.pointcustomPage.currentPage = currentPage;
        this.pointcustomOnLoad(this.pointcustomPage);
      },

      // 巡检点换每页显示数量
      pointcustomSizeChange(pageSize){
        this.pointcustomPage.pageSize = pageSize;
        this.pointcustomOnLoad(this.pointcustomPage);
      },

      // 选择巡检点
      choosePointcustom() {
        var pageSelectIds = [];
        var pageAllIds = [];
        this.pointcustomSelectionList.forEach(item => {
          this.selectPointcustom[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.pointcustomData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectPointcustom) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectPointcustom[id];
          }
        }
        if(this.selectPointcustom === undefined || JSON.stringify(this.selectPointcustom) === "{}") {
          this.$message.warning("请选择巡检点");
          return;
        }
        this.pointcustomTagsErr = false;
        this.pointcustomTags = [];
        for(let id in this.selectPointcustom) {
          this.pointcustomTags.push(this.selectPointcustom[id]);
        }
        this.closeDialog();
      },

      // 删除某一个巡检点
      closePointcustomTag(index) {
        this.pointcustomTags.splice(index, 1);
        if(this.pointcustomTags.length === 0) {
          this.pointcustomTagsErr = true;
        }
      },

      abc(val)
      {
        console.log(val)
      },
      rowSave(row, done, loading) {
        if (this.personData.length === 0) {
          this.$message.warning("请添加任务时间!");
          loading();
          return;
        }
        var isEmpty = false;
        this.personData.forEach(item => {
          if (
            item.qssj === "" ||
            item.qssj === undefined ||
            item.jssj === "" ||
            item.jssj === undefined
          ) {
            isEmpty = true;
          }
        });
        if (isEmpty) {
          this.$message.warning("请填写正确的任务时间");
          loading();
          return;
        }
        for (let key in row) {
          if (key.indexOf("$") >= 0) {
            console.log(key)
            delete row[key];
          }
        }
        row["taskTimeSettings"] = [];
        this.personData.forEach(item => {
          var measure = {
            qssj: item.qssj,
            jssj: item.jssj,
          };
          if (item.id !== "" && item.id !== undefined) {
            measure["id"] = item.id;
          }
          row.taskTimeSettings.push(measure);
        });

        if(this.pointcustomTags.length === 0) {
          this.pointcustomTagsErr = true;
          loading();
          return;
        }
        delete row.dwmc;
        var idsArr = [];
        this.pointcustomTags.forEach(item => {
          idsArr.push(item.id);
        });
        row.ids = idsArr.join(",");

        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (this.personData.length === 0) {
          this.$message.warning("请添加任务时间!");
          loading();
          return;
        }
        var isEmpty = false;
        this.personData.forEach(item => {
          if (
            item.qssj === "" ||
            item.qssj === undefined ||
            item.jssj === "" ||
            item.jssj === undefined
          ) {
            isEmpty = true;
          }
        });
        if (isEmpty) {
          this.$message.warning("请填写正确的时间信息");
          loading();
          return;
        }
        for (let key in row) {
          if (key.indexOf("$") >= 0) {
            console.log(key)
            delete row[key];
          }
        }
        row["taskTimeSettings"] = [];
        this.personData.forEach(item => {
          var measure = {
            qssj: item.qssj,
            jssj: item.jssj,
          };
          if (item.id !== "" && item.id !== undefined) {
            measure["id"] = item.id;
          }
          row.taskTimeSettings.push(measure);
        });

        if(this.pointcustomTags.length === 0) {
          this.pointcustomTagsErr = true;
          loading();
          return;
        }
        var idsArr = [];
        var updateData = {
          id: row.id,
          xm: row.xm,
          szbm: row.szbm,
          gwmc: row.gwmc,
          gh: row.gh,
          lxdh: row.lxdh,
          bzqtcy:row.bzqtcy,
          jcpc: row.jcpc,
          jccs: row.jccs,
          bladeDeptId: row.bladeDeptId,
          tenantId: row.tenantId,
          createUser: row.createUser,
          createDept: row.createDept,
          createTime: row.createTime,
          isDeleted:row.isDeleted,
          ids: "",
          taskTimeSettings: row.taskTimeSettings,
        };
        this.pointcustomTags.forEach(item => {
          idsArr.push(item.id);
        });
        updateData.ids = idsArr.join(",");

        update(updateData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this. pointcustomTagsErr = false;
        this.pointcustomTags = [];
        this.selectPointcustom = {};
        this.dialogType = type;
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.form.pointCustomSettings.forEach(item => {
              this.pointcustomTags.push(item);
              this.selectPointcustom[item.id] = item;
            });
            this.personData = this.form.taskTimeSettings
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .dwryxxContent_div {
    .avue-crud {
      .el-table__empty-block,
      .el-table__header-wrapper,
      .avue-crud__menu,
      .avue-crud__pagination {
        display: none;
      }
    }
  }
  .warehousearea {
    .el-form-item__label {
      width: 120px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 120px !important;
      }
    }
  }
</style>
